package com.zc.im.netty.codec;

import com.zc.im.common.constant.enums.MsgTypeEnum;
import com.zc.im.common.constant.enums.MsgTypeEnumContext;
import com.zc.im.common.msg.Msg;
import com.zc.im.common.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Project：im
 * Date：2022/4/21
 * Time：14:21
 * Description：im自定义解码器
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public class ImDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        //读取指令
        byte command = byteBuf.readByte();
        //指令占了一位，剔除掉
        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);
        Class<? extends Msg> aClass = MsgTypeEnumContext.getClazz(command);
        if (aClass != null) {
            list.add(ProtostuffUtil.deserializer(data, aClass));
        }

    }
}
